﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GDoc.Domain.Services;
using System.IO;
using GDoc.Web.Models;
using GDoc.Domain;
using GDoc.Utils;
using System.Text;

namespace GDoc.Web.Controllers
{
    [Authorize]
    public class FilesController : _ControllerBase
    {
        [HttpGet]
        public ActionResult Browse(string path)
        {
            path = path ?? string.Empty;

            Account account = GetCurrentAccount();

            if (account == null)
                return RedirectToAction("Index", "Home");

            FilesBrowseModel model = new FilesBrowseModel
            {
                Account = account,
                Path = path,
                DirectoryTree = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
            };

            return View(model);
        }

        [HttpPost]
        public JsonResult CreateFolder(string name, string path)
        {
            Account account = GetCurrentAccount();

            if (account == null)
                return Json(null);

            FileSystemEntry entry = FileSystem.CreateFolder(account.Id, name, path);

            return Json(new FileSystemEntryModel(entry, ControllerContext.RequestContext));
        }

        [HttpGet]
        [OutputCache(NoStore=true, Duration=0)]
        public JsonResult GetFiles(string path, string sEcho, int iSortCol_0, string sSortDir_0)
        {
            Account account = GetCurrentAccount();

            if (account == null)
                return Json(null);

            IEnumerable<FileSystemEntry> entries = FileSystem.Browse(account.Id, path);

            var query = entries.AsQueryable();

            switch (iSortCol_0)
            {
                case 0: { query = (sSortDir_0 == "asc" ? query.OrderBy(e => e.Name) : query.OrderByDescending(e => e.Name)); } break;
                case 1: { query = (sSortDir_0 == "asc" ? query.OrderByDescending(e => e.Type) : query.OrderBy(e => e.Type)); } break;
                case 2: { query = (sSortDir_0 == "asc" ? query.OrderBy(e => e.Size) : query.OrderByDescending(e => e.Size)); } break;
                case 3: { query = (sSortDir_0 == "asc" ? query.OrderBy(e => e.Modified) : query.OrderByDescending(e => e.Modified)); } break;
                default: break;
            }
            
            return Json(new
            {
                sEcho = sEcho,
                aaData = query.Select(e => new FileSystemEntryModel(e, ControllerContext.RequestContext))
            }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult Upload(string path)
        {
            Account account = GetCurrentAccount();

            if (account == null)
                return Json(null);

            List<FileSystemEntry> entries = new List<FileSystemEntry>();

            var files = Request.Files;

            for (int i = 0; i < files.Count; i++)
            {
                var file = files[0];

                //if (file.ContentLength > 0)
                //{
                    var fileName = Path.GetFileName(file.FileName);

                    var entry = FileSystem.CreateFile(account.Id, fileName, path, file.ContentType, file.ContentLength);

                    FileSystem.UploadFileContent(account.Id, entry.FullPath, file.InputStream);
                    
                    entries.Add(entry);
                //}
            }

            return Json(new
            {
                aaData = entries.Select(e => new FileSystemEntryModel(e, ControllerContext.RequestContext))
            }, JsonRequestBehavior.AllowGet);


        }

        [HttpGet]
        public ActionResult GetFile(string path)
        {
            Account account = GetCurrentAccount();

            if (account == null)
                return RedirectToAction("Index", "Home");

            FileSystemEntry entry = FileSystem.GetFile(account.Id, path);

            if (entry != null)
            {
                Stream content = FileSystem.GetFileContent(account.Id, path);

                if (content != null)
                    return File(content, entry.ContentType, entry.Name);
            }

            return HttpNotFound();
        }

        [HttpPost]
        public JsonResult Remove(string path)
        {
            Account account = GetCurrentAccount();

            if (account == null)
                return Json(null);

            FileSystem.Remove(account.Id, path);

            return Json(null);
        }
    }
}
